package com.example.backed.service.impl;

import com.example.backed.dto.CartItemAddDTO;
import com.example.backed.entity.CartItem;
import com.example.backed.entity.Product;
import com.example.backed.exception.BusinessException;
import com.example.backed.mapper.CartItemMapper;
import com.example.backed.mapper.ProductMapper;
import com.example.backed.service.CartService;
import com.example.backed.vo.CartStatsVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
@RequiredArgsConstructor
public class CartServiceImpl implements CartService {

    private final CartItemMapper cartItemMapper;
    private final ProductMapper productMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CartItem addToCart(Long userId, CartItemAddDTO addDTO) {
        // 1. 查询商品信息
        Product product = productMapper.findById(addDTO.getProductId());
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        if (product.getStatus() != 1) {
            throw new BusinessException("商品已下架");
        }
        if (product.getStock() < addDTO.getQuantity()) {
            throw new BusinessException("商品库存不足");
        }

        // 2. 查询购物车中是否已存在该商品
        CartItem existingItem = cartItemMapper.findByUserIdAndProductId(userId, addDTO.getProductId());
        if (existingItem != null) {
            // 2.1 如果存在，更新数量
            int newQuantity = existingItem.getQuantity() + addDTO.getQuantity();
            if (product.getStock() < newQuantity) {
                throw new BusinessException("商品库存不足");
            }
            cartItemMapper.updateQuantity(existingItem.getId(), newQuantity);
            existingItem.setQuantity(newQuantity);
            return existingItem;
        }

        // 3. 如果不存在，创建新的购物车项
        CartItem cartItem = new CartItem();
        cartItem.setUserId(userId);
        cartItem.setProductId(product.getId());
        cartItem.setProductName(product.getName());
        cartItem.setProductImage(product.getImage());
        cartItem.setPrice(product.getPrice());
        cartItem.setQuantity(addDTO.getQuantity());
        cartItem.setSelected(1); // 默认选中
        cartItemMapper.insert(cartItem);

        return cartItem;
    }

    @Override
    public boolean updateQuantity(Long userId, Long id, Integer quantity) {
        // 1. 查询购物车项
        CartItem cartItem = cartItemMapper.findByUserId(userId).stream()
                .filter(item -> item.getId().equals(id))
                .findFirst()
                .orElseThrow(() -> new BusinessException("购物车项不存在"));

        // 2. 验证商品库存
        Product product = productMapper.findById(cartItem.getProductId());
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        if (product.getStock() < quantity) {
            throw new BusinessException("商品库存不足");
        }

        // 3. 更新数量
        return cartItemMapper.updateQuantity(id, quantity) > 0;
    }

    @Override
    public boolean updateSelected(Long userId, Long id, Integer selected) {
        // 1. 验证购物车项是否属于当前用户
        CartItem cartItem = cartItemMapper.findByUserId(userId).stream()
                .filter(item -> item.getId().equals(id))
                .findFirst()
                .orElseThrow(() -> new BusinessException("购物车项不存在"));

        // 2. 更新选中状态
        return cartItemMapper.updateSelected(id, selected) > 0;
    }

    @Override
    public boolean deleteCartItem(Long userId, Long id) {
        // 1. 验证购物车项是否属于当前用户
        CartItem cartItem = cartItemMapper.findByUserId(userId).stream()
                .filter(item -> item.getId().equals(id))
                .findFirst()
                .orElseThrow(() -> new BusinessException("购物车项不存在"));

        // 2. 删除购物车项
        return cartItemMapper.deleteById(id) > 0;
    }

    @Override
    public List<CartItem> getUserCartItems(Long userId) {
        return cartItemMapper.findByUserId(userId);
    }

    @Override
    public List<CartItem> getSelectedCartItems(Long userId) {
        return cartItemMapper.findSelectedByUserId(userId);
    }

    @Override
    public boolean clearCart(Long userId) {
        return cartItemMapper.deleteByUserId(userId) > 0;
    }

    @Override
    public boolean deleteSelectedItems(Long userId) {
        return cartItemMapper.deleteSelectedByUserId(userId) > 0;
    }

    @Override
    public CartStatsVO getCartStats(Long userId) {
        // 1. 获取用户的所有购物车项
        List<CartItem> cartItems = cartItemMapper.findByUserId(userId);
        
        // 2. 创建统计对象
        CartStatsVO stats = new CartStatsVO();
        
        // 3. 如果购物车为空，直接返回
        if (cartItems.isEmpty()) {
            return stats;
        }
        
        // 4. 统计数据
        for (CartItem item : cartItems) {
            // 4.1 累加总数量和总金额
            stats.setTotalQuantity(stats.getTotalQuantity() + item.getQuantity());
            BigDecimal itemAmount = item.getPrice().multiply(new BigDecimal(item.getQuantity()));
            stats.setTotalAmount(stats.getTotalAmount().add(itemAmount));
            
            // 4.2 如果是选中的商品，累加选中的数量和金额
            if (item.getSelected() == 1) {
                stats.setSelectedQuantity(stats.getSelectedQuantity() + item.getQuantity());
                stats.setSelectedAmount(stats.getSelectedAmount().add(itemAmount));
                stats.setSelectedItemCount(stats.getSelectedItemCount() + 1);
            }
        }
        
        // 4.3 设置商品种类数量
        stats.setItemCount(cartItems.size());
        
        return stats;
    }
} 